package topsun.rms.web;

import java.util.Hashtable;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import topsun.framework.utility.HqlFilter;
import topsun.rms.entity.DataDictionary;
import topsun.rms.entity.Item;
import topsun.rms.entity.ItemType;
import topsun.rms.entity.Unit;
import topsun.rms.entity.UserRole;
import topsun.rms.model.Pager;
import topsun.rms.services.IBaseService;
import topsun.rms.services.IUserRoleService;
import topsun.rms.services.IItemService;

@Controller
@RequestMapping("datapage/item")
public class ItemController extends BaseController<Item>
{
	
	protected Hashtable<String, String> unitList = new Hashtable<>();
	protected Hashtable<String, String> itemTypeList = new Hashtable<>();
	
	@Resource(name = "itemService")  
	public void setService(IBaseService<Item> Service1) 
	{  
		super.setService(Service1);
	}
	
	@Resource(name = "unitService")   
	private IBaseService<Unit> unitService;
	
	@Resource(name = "itemTypeService")   
	private IBaseService<ItemType> itemTypeService;
	
	private void getDictionarys()
	{
		unitList.clear(); itemTypeList.clear();
		for (ItemType itemType : itemTypeService.find()) 
		{
			itemTypeList.put(itemType.getId(), itemType.getName());
		}
		for (Unit unit : unitService.find()) 
		{
			unitList.put(unit.getId(), unit.getName());
		}
	}
	@Override
	protected void grid(HttpServletRequest request, HttpServletResponse response) 
	{
		getDictionarys();  //temp
		parseRequest(request);
		
		Pager pager = new Pager();
		HqlFilter hqlFilter = new HqlFilter(request);
		pager.setTotal(service.countByFilter(hqlFilter));
		
		List<Item> items = service.findByFilter(hqlFilter, page, rows);
		//字典转换
		for (Item item : items)
		{
			String itemType  = item.getItemtype() ;
			if(StringUtils.isBlank(itemType)) continue;
			if(itemTypeList.containsKey(itemType)) 
			{
				item.setItemtype(itemTypeList.get(itemType));
			}
			
			String unit  = item.getUnit();
			if(StringUtils.isBlank(unit)) continue;
			if(unitList.containsKey(unit)) 
			{
				item.setUnit(unitList.get(unit));
			}
		}
		
		pager.setRows(items);
		writeJson(pager, request, response);
	}
	@RequestMapping(value = "/getbyitemid", method = RequestMethod.POST)
	public void getItemByPromotionId( HttpServletRequest request, HttpServletResponse response)
	{
		parseRequest(request);
		HqlFilter hqlFilter = new HqlFilter(request);   
		hqlFilter.addFilter("QUERY_promotion#id_I_EQ",id.toString());
		List<Item> items =((IItemService)service).findItemByFilter(hqlFilter);
		writeJson(items,request,response);
	}

	
}
